package repository;


import java.io.IOException;
import java.util.ArrayList;
import java.util.Hashtable;

import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;


/**
 * Reads the music in from file.
 * @author 0800542m
 *
 */
public class MusicReader {
	
	//Keeps the information parsed from file once reading is finished.
	ParseHandler handler;
	
	
	//Constructor
	/**
	 * Creates a MusicReader that parses a given file.
	 * @param filename Name of file to be parsed.
	 */
	protected MusicReader(String filename){
		read(filename);
	}
	
	
	//Methods used by package
	/**
	 * Returns all music parsed from file given in constructor.
	 * @return parsed music.
	 */
	protected Hashtable<Integer, ArrayList<Note>> getMusic(){
		return handler.getMusicResults();
	}
	
	/**
	 * Returns song length parsed from file given in constructor.
	 * @return parsed song length.
	 */
	protected int getSongLength(){
		return handler.getSongLength();
	}
	
	
	//Private methods.
	/**
	 * Reads in all info from a specified file.
	 * @param filename Name of an xml file complying with the required formatting.
	 * @return Hashtable containing the pieces of all instruments extracted from filename.
	 */
	private void read(String filename){
		
		handler = new ParseHandler();
		
		//Code as required to parse a given file.
		try{
			XMLReader parser = XMLReaderFactory.createXMLReader();	
			parser.setContentHandler(handler);
			parser.parse(filename);
		}
		catch(IOException e){
			System.out.println("Error reading URI: "+e.getMessage());
			System.exit(-1);
		}
		catch(SAXException e){
			System.out.println("Error parsing XML file: "+e.getMessage());
			System.exit(-1);
		}
		
	}

}
